package com.app.controller;

import com.app.common.EducationTool;
import com.app.common.ScaleTool;
import com.app.model.*;
import com.app.service.*;
import com.app.util.*;
import com.app.vo.LookMeVo;
import com.app.vo.ScaleVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;


@Controller
@RestController
public class LookMeController {

    @Autowired
    CustomerService customerService;
    @Autowired
    UserService userService;
    @Autowired
    ComRecruitersService comRecruitersService;
    @Autowired
    LookMeService lookMeService;
    @Autowired
    EnterpriseService enterpriseService;

    @Autowired
    IndustryService industryService;
    @Autowired
    JobPublishService jobPublishService;
    @Autowired
    CusEducationService cusEducationService;
    @Autowired
    CusWorkExperienceService cusWorkExperienceService;
    @Autowired
    WorkApplyService workApplyService;

    /**
     * 根据token查询用户
     */
    @PostMapping("/insertLookMe")//新增收藏关注
    public Result<Object> insertMyCollect(@RequestParam(required = false) Integer pid,
                                          @RequestParam("userType") int userType,
                                          @RequestParam(required = false) Integer cid,
                                          @RequestParam(required = false) Integer eid,
                                          @RequestParam(required = false) Integer lookMeType,
                                          @RequestParam(required = false) Integer state,
                                          HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        if (userType == 1) {
            CustomerModel cus = customerService.getCustomerById(user.getCId());//拿cid
            JobPublishModel jobPublish = null;
            int rid = 0;
            if (eid == null&&lookMeType!=3) {
                jobPublish = jobPublishService.findAllJobById(pid);//根据pid拿rid(hr)
                if(jobPublish==null)
                {
                    return null;
                }
                ComRecruitersModel com = comRecruitersService.getComRecruitersById(jobPublish.getRecId());//根据hrId拿公司Id
                eid = com.getComId();
                rid = jobPublish.getRecId();
            }
            if (pid == null) {
                pid = 0;
            }
            if (eid == null) {
                eid = 0;
            }
            LookMeModel model = lookMeService.findRidAndPid(pid, rid, eid, cus.getId(), userType, lookMeType);//根据hrId和岗位pid判空
            if (lookMeType == 1) {
                if (model != null) {
                    return Result.success(null);
                }
            }
            model = new LookMeModel();//因上面为空需重新new
            if (pid == null) {
                pid = 0;
            }
            model.setPid(pid);
            model.setRid(rid);
            model.setEid(eid);
            model.setUserType(userType);
            model.setCid(cus.getId());
            model.setLookMeType(lookMeType);
            model.setCrtTime(String.valueOf(CommonHelp.getNowTimestamp()));
            if (state == 1) {
                lookMeService.delete(model);
            } else if (state == 2) {
                lookMeService.insert(model);
            }
        } else if (userType == 2) {
            if (pid == null) {
                pid = 0;
            }
            ComRecruitersModel com = comRecruitersService.getComRecruitersById(user.getRId());//根据token拿rid(hrId)
            LookMeModel model = lookMeService.findRidAndPid(pid, com.getId(), com.getComId(), cid, userType, lookMeType);//根据hrId和岗位pid判空
            if (lookMeType == 1) {
                if (model != null) {
                    return Result.success(null);

                }
            }
            model = new LookMeModel();//因上面为空需重新new
            model.setLookMeType(lookMeType);
            model.setRid(com.getId());
            model.setCid(cid);
            model.setEid(com.getComId());//公司id
            model.setUserType(userType);
            model.setCrtTime(String.valueOf(CommonHelp.getNowTimestamp()));
            if (state == 1) {
                lookMeService.delete(model);

            } else if (state == 2) {
                lookMeService.insert(model);

            }
        }
        return Result.success(null);

    }

    @RequestMapping("/lookMeGetByCidList")//hr端个人中心userType=2
    public Result<Object> LookMeGetByCidList(
            @RequestParam("lookMeType") int lookMeType,
            @RequestParam("userType") int userType,
            @RequestParam("page") int page,
            @RequestParam("limit") int limit,
            HttpServletRequest request) throws ParseException {

        JSONObject json = new JSONObject();
        String token = request.getHeader("token");
//        String id = request.getParameter("id");
        if (token == null) {
            return Result.error(405, "token不存在");

        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");

        }
        List<LookMeModel> lookMeList;
        int count = 0;
        if (userType == 1) {
            Page<LookMeModel> lookMeModelPage = lookMeService.findLookMeList(2, lookMeType, user.getCId(), 0,page,limit);
            lookMeList = lookMeModelPage.getRecords();
            count = (int)lookMeModelPage.getTotal();
        } else {
            ComRecruitersModel com = comRecruitersService.getComRecruitersById(user.getRId());
            if (lookMeType == 1) {
                Page<LookMeModel> lookMeModelPage = lookMeService.findLookMeList(1, lookMeType, 0, com.getComId(),page,limit);
                lookMeList = lookMeModelPage.getRecords();
                count = (int)lookMeModelPage.getTotal();
            } else {
                Page<LookMeModel> lookMeModelPage = lookMeService.findLookMeList(2, lookMeType, 0, com.getComId(),page,limit);
                lookMeList = lookMeModelPage.getRecords();
                count = (int)lookMeModelPage.getTotal();
            }

        }
        if (lookMeList != null) {
            for (int i = 0; i < lookMeList.size(); i++) {
                CustomerModel cus = customerService.getCustomerById(lookMeList.get(i).getCid());
//            lookMeList.get(i).setCus(cus);
                //计算年龄
                Timestamp time = new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(cus.getBirthday() + "-01").getTime());
                String date = DateUtil.yearCompare(time, CommonHelp.getNowTimestamp());
                cus.setBirthday(date);
                //判断性别
                if (cus.getSex() == 1) {
                    cus.setSexText("男");
                } else {
                    cus.setSexText("女");
                }
                if (StringTool.isEmpty(cus.getJobText())) {
                    cus.setJobText("暂无状态");
                }
                //学历
                List<CusEducationModel> education = cusEducationService.getEducationByCustomerId(cus.getId());
                String eduName = "";
                if (education != null && education.size() > 0)//学历
                {
//                        cus.setEducation(education.get(0).getEducation());
                    for (int k = 0; k < EducationTool.EDUCATION_VO_LIST.size(); k++) {
                        if (education.get(0).getEducation() == EducationTool.EDUCATION_VO_LIST.get(k).getId()) {
                            cus.setEducation(EducationTool.EDUCATION_VO_LIST.get(k).getData());
                        }
                    }
                    if (cus.getEducation() == null || cus.getEducation() == "") {
                        cus.setEducation("暂无学历");
                    }
                } else {
                    cus.setEducation("暂无学历");
                }
                //工作经验
                List<CusWorkExperienceModel> workExpList = cusWorkExperienceService.getWorkExpByCustomerId(cus.getId());

                if (workExpList != null && workExpList.size() > 0) {
                    Timestamp time2 = new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(workExpList.get(0).getWorkTimeStart() + "-01").getTime());
                    String date2 = DateUtil.yearCompare(time2, CommonHelp.getNowTimestamp());
                    cus.setWorkTimeStart(date2 + "年");
                } else {
                    cus.setWorkTimeStart("无经验");
                }
                if (cus.getJobStatus() == 1) {
                    cus.setJobText("离职-随时到岗");
                } else if (cus.getJobStatus() == 2) {
                    cus.setJobText("在职-月内到岗");
                } else if (cus.getJobStatus() == 3) {
                    cus.setJobText("在职-考虑机会");
                } else if (cus.getJobStatus() == 4) {
                    cus.setJobText("在职-暂不考虑");
                }else{
                    cus.setJobText("暂无状态");
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Timestamp data = Timestamp.valueOf(lookMeList.get(i).getCrtTime());
                String crtTime = sdf.format(data);
                lookMeList.get(i).setFormatTime(crtTime);
                UserModel cusUser = userService.getUserByCustomerId(cus.getId());
                cus.setUser(cusUser);
                lookMeList.get(i).setCus(cus);
            }
        }
        LookMeVo vo = new LookMeVo();
        vo.setCount(count);
        vo.setList(lookMeList);
        return Result.success(vo);
    }

    @RequestMapping("lookMeFindByCidList")//个人中心用户端userType=1
    public Result<Object> LookMeFindByCidList(
            @RequestParam("lookMeType") int lookMeType,
            @RequestParam("userType") int userType,
            @RequestParam("page") int page,
            @RequestParam("limit") int limit,
            HttpServletRequest request) throws ParseException {

        String token = request.getHeader("token");
//        String id = request.getParameter("id");
        if (token == null) {
            return Result.error(405, "token不存在");

        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        List<LookMeModel> lookMeList;
        int count = 0;
        if (userType == 1) {
            if(lookMeType==1)
            {
                userType = 2;
            }
            Page<LookMeModel> lookMePage = lookMeService.findLookMeList(userType, lookMeType, user.getCId(), 0,page,limit);
            lookMeList = lookMePage.getRecords();
            count = (int)lookMePage.getTotal();
        } else {
            if(lookMeType==1)
            {
                userType = 1;
            }
            ComRecruitersModel com = comRecruitersService.getComRecruitersById(user.getRId());
            Page<LookMeModel> lookMePage = lookMeService.findLookMeList(userType, lookMeType, 0, com.getComId(),page,limit);
            lookMeList = lookMePage.getRecords();
            count = (int)lookMePage.getTotal();
        }
        if (lookMeList != null) {
            for (int i = 0; i < lookMeList.size(); i++) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Timestamp data = Timestamp.valueOf(String.valueOf(lookMeList.get(i).getCrtTime()));
                String crtTime = sdf.format(data);
                lookMeList.get(i).setCrtTime(crtTime);
            }
        }

        if (lookMeType == 1) {//查询谁看过我(Hr)
            if (lookMeList != null) {
                for (int i = 0; i < lookMeList.size(); i++) {
                    JobPublishModel publish = jobPublishService.findJobName(lookMeList.get(i).getPid());
                    ComRecruitersModel com = comRecruitersService.getComRecruitersById(lookMeList.get(i).getRid());//根据lookmeList查询到的hrid去查hr信息
                    EnterpriseModel ent = enterpriseService.findLogoById(com.getComId());
                    ent.setJobPublishModel(publish);
                    com.setEnterprise(ent);
                    UserModel userByRId = userService.getUserByRId(lookMeList.get(i).getRid());
                    com.setUser(userByRId);
                    lookMeList.get(i).setCom(com);//查询出来信息
                }
            }

        } else if (lookMeType == 2) {//查询我的关注
            if (lookMeList != null) {
                for (int i = 0; i < lookMeList.size(); i++) {
                    EnterpriseModel ent = enterpriseService.findModelById(lookMeList.get(i).getEid());//根据企业eid去查企业名称和logo
                    ScaleVo scaleVo = new ScaleVo();
                    for (int j = 0; j < ScaleTool.SCALE_VO_LIST.size(); j++) {
                        if (ScaleTool.SCALE_VO_LIST.get(j).getId() == ent.getScaleId()) {
                            scaleVo = ScaleTool.SCALE_VO_LIST.get(j);
                        }
                    }
                    IndustryModel industryModel = industryService.getModelByCode(ent.getEnterpriseType());
                    ent.setEnterpriseTypeText(industryModel.getIndustryName());
                    ent.setScaleName(scaleVo.getData());
                    lookMeList.get(i).setEnt(ent);
                }
            }

        } else if (lookMeType == 3) {//查询我的收藏
            if (lookMeList != null) {
                for (int i = 0; i < lookMeList.size(); i++) {
                    JobPublishModel publish = jobPublishService.findAllJobById(lookMeList.get(i).getPid());
                    if (publish != null) {
                        ComRecruitersModel com = comRecruitersService.getComRecruitersById(publish.getRecId());
                        if (com != null) {
                            EnterpriseModel enterprise = enterpriseService.findModelById(com.getComId());
                            IndustryModel industryModel = industryService.getModelByCode(enterprise.getEnterpriseType());
                            enterprise.setEnterpriseTypeText(industryModel.getIndustryName());
                            com.setEnterprise(enterprise);
                            com.setUser(userService.getUserByRId(com.getId()));
                            publish.setComRecruiters(com);
                        }
                    }
                    lookMeList.get(i).setJobPublish(publish);

                }
            }

        }

        LookMeVo vo = new LookMeVo();
        vo.setList(lookMeList);
        vo.setCount(count);
        return Result.success(vo);
    }

    @PostMapping("getLookMeCount")
    public Result<Object> getLookMeCount(HttpServletRequest request) throws ParseException {
        JSONObject json = new JSONObject();
        String token = request.getHeader("token");
        int type = Integer.valueOf(request.getParameter("type"));//判断是个人还是公司
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        TokenUtils tokenUtil = new TokenUtils();
        String mobile = tokenUtil.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");

        }
        LookMeModel lookMeModel = new LookMeModel();
        if (type == 1) {
            CustomerModel cus = customerService.getCustomerById(user.getCId());
            //统计个人关注
            LookMeModel lookMe = new LookMeModel();
            lookMe.setCid(cus.getId());
            lookMe.setLookMeType(2);
            lookMe.setUserType(1);
            int followCount = lookMeService.selectAllCount(0, lookMe.getCid(), lookMe.getUserType(), lookMe.getLookMeType());
            lookMeModel.setFollowCount(followCount);
            //统计个人收藏
            LookMeModel lookMe2 = new LookMeModel();
            lookMe2.setCid(cus.getId());
            lookMe2.setLookMeType(3);
            lookMe2.setUserType(1);
            int favouriteCount = lookMeService.selectAllCount(0, lookMe2.getCid(), lookMe2.getUserType(), lookMe2.getLookMeType());
            lookMeModel.setFavouriteCount(favouriteCount);
            //统计个人谁看过我
            LookMeModel lookMe3 = new LookMeModel();
            lookMe3.setCid(cus.getId());
            lookMe3.setLookMeType(1);
            lookMe3.setUserType(2);
            int lookMeCount = lookMeService.selectAllCount(0, lookMe3.getCid(), lookMe3.getUserType(), lookMe3.getLookMeType());
            lookMeModel.setLookMeCount(lookMeCount);
            //投递过的简历数量
            Page<WorkApplyModel> workApplyPage = workApplyService.getWorkApplyByCustomerId(cus.getId(),1,100);

            lookMeModel.setDeliveryCount((int)workApplyPage.getTotal());
            return Result.success(lookMeModel);
        } else {
            ComRecruitersModel com = comRecruitersService.getComRecruitersById(user.getRId());
            //统计HR关注
            LookMeModel lookMe = new LookMeModel();
            lookMe.setEid(com.getComId());
            lookMe.setLookMeType(2);
            lookMe.setUserType(2);
            int followCount = lookMeService.selectAllCount(lookMe.getEid(), 0, lookMe.getUserType(), lookMe.getLookMeType());
            lookMeModel.setFollowCount(followCount);
            //统计Hr谁看过我
            LookMeModel lookMe2 = new LookMeModel();
            lookMe2.setEid(com.getComId());
            lookMe2.setLookMeType(1);
            lookMe2.setUserType(1);
            int lookMeCount = lookMeService.selectAllCount(lookMe2.getEid(), 0, lookMe2.getUserType(), lookMe2.getLookMeType());
            lookMeModel.setLookMeCount(lookMeCount);

            //收到的简历数量
            Page<WorkApplyModel> list = workApplyService.getWorkApplyByComId(com.getComId(),0,0);
            if (list == null) {
                lookMeModel.setDeliveryCount(0);
            } else {
                lookMeModel.setDeliveryCount((int)list.getTotal());
            }
            //发布岗位数量
            JobPublishModel jobPublish = new JobPublishModel();
            jobPublish.setRecId(com.getId());
            int jobPublishCount = jobPublishService.getJobPublishCountByModel(jobPublish);
            lookMeModel.setJobPublishCount(jobPublishCount);
            return Result.success(lookMeModel);
        }
    }
}
